package org.mc.domainservice;

import com.google.common.collect.Lists;
import org.mc.bean.UserCenterEntity;
import org.mc.common.data.PagedDTO;
import org.mc.common.util.BeanUtils;
import org.mc.repository.UserCenterRepository;
import org.mc.response.user.CustomerDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserCenterDomainService {

    @Autowired
    private UserCenterRepository userCenterRepository;

    /**
     * 根据用户id查询
     *
     * @param userId
     * @return
     */
    public UserCenterEntity getUser(long userId) {
        return userCenterRepository.findOne(userId);
    }

    /**
     * 分页查询
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public PagedDTO<List<CustomerDTO>> listAll(int pageIndex, int pageSize) {
        PagedDTO<List<CustomerDTO>> pagedDTO = new PagedDTO<>();
        Pageable pageable = new PageRequest(pageIndex, pageSize, new Sort(Sort.Direction.DESC, "createTime"));
        Page page = userCenterRepository.findAll(((root, query, cb) -> {
            List<Predicate> list = Lists.newArrayList();
            /*if (userId == null) {
                throw new BaseException("用户id,不能为空!");
            }
            list.add(cb.equal(root.get("userId"), userId));*/

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        }), pageable);

        List<CustomerDTO> list = (List<CustomerDTO>) page.getContent().stream().map(rs -> {
            return BeanUtils.convert(rs, CustomerDTO.class);
        }).collect(Collectors.toList());

        pagedDTO.setPageIndex(page.getNumber());
        pagedDTO.setPageSize(page.getTotalPages());
        pagedDTO.setCount(page.getTotalElements());
        pagedDTO.setList(list);
        return pagedDTO;
    }
}
